<template>
  <div class="analytics-container">
    <h2>数据分析</h2>
    
    <!-- 数据概览卡片 -->
    <el-row :gutter="20" class="data-overview">
        <el-col :span="6">
        <el-card shadow="hover">
          <template #header>
            <div class="card-header">
              <span>总任务数</span>
            </div>
          </template>
          <div class="card-value">{{ statistics.totalTasks }}</div>
          </el-card>
        </el-col>
      
        <el-col :span="6">
        <el-card shadow="hover">
          <template #header>
            <div class="card-header">
              <span>活跃企业数</span>
            </div>
          </template>
          <div class="card-value">{{ statistics.activeCompanies }}</div>
          </el-card>
        </el-col>
      
        <el-col :span="6">
        <el-card shadow="hover">
          <template #header>
            <div class="card-header">
              <span>委托成交数</span>
            </div>
          </template>
          <div class="card-value">{{ statistics.completedTasks }}</div>
          </el-card>
        </el-col>
      
        <el-col :span="6">
        <el-card shadow="hover">
          <template #header>
            <div class="card-header">
              <span>平均任务报酬</span>
            </div>
          </template>
          <div class="card-value">¥{{ statistics.averageSalary }}</div>
          </el-card>
        </el-col>
      </el-row>
      
    <!-- 图表区域 -->
    <el-row :gutter="20" class="charts-container">
      <!-- 工种分布分析 -->
      <el-col :span="12">
        <el-card shadow="hover">
            <template #header>
            <div class="card-header">
              <span>工种分布分析</span>
              </div>
            </template>
          <div ref="typeChart" class="chart"></div>
          </el-card>
        </el-col>
        
      <!-- 委托成交分析 -->
      <el-col :span="12">
        <el-card shadow="hover">
          <template #header>
            <div class="card-header">
              <span>委托成交分析</span>
            </div>
          </template>
          <div ref="statusChart" class="chart"></div>
        </el-card>
      </el-col>
    </el-row>
    
    <!-- 薪资趋势 -->
    <el-row :gutter="20" class="charts-container">
      <el-col :span="24">
        <el-card shadow="hover">
            <template #header>
            <div class="card-header">
              <span>平台工资趋势</span>
              <el-select v-model="salaryTrendPeriod" size="small" @change="updateSalaryTrend">
                    <el-option label="最近7天" value="7days" />
                    <el-option label="最近30天" value="30days" />
                    <el-option label="最近3个月" value="3months" />
                  </el-select>
              </div>
            </template>
          <div ref="salaryTrendChart" class="chart"></div>
          </el-card>
        </el-col>
      </el-row>
      
    <!-- 工种平均工资对比 -->
    <el-row :gutter="20" class="charts-container">
      <el-col :span="24">
        <el-card shadow="hover">
            <template #header>
            <div class="card-header">
              <span>工种平均工资对比</span>
              </div>
            </template>
          <div ref="salaryComparisonChart" class="chart"></div>
          </el-card>
        </el-col>
    </el-row>
        
    <!-- 任务列表 -->
    <el-card shadow="hover" class="task-list-card">
            <template #header>
        <div class="card-header">
          <span>任务列表</span>
              </div>
            </template>
      
            <el-table
        :data="tasks"
              style="width: 100%"
        @row-click="handleRowClick"
        v-loading="loading"
      >
        <el-table-column prop="title" label="任务标题" />
        <el-table-column prop="jobType" label="任务类型" width="120" />
        <el-table-column prop="location" label="工作地点" width="150" />
        <el-table-column prop="salary" label="报酬" width="100">
          <template #default="scope">
            ¥{{ scope.row.salary }}
          </template>
        </el-table-column>
        <el-table-column prop="status" label="状态" width="100">
          <template #default="scope">
            <el-tag :type="getStatusType(scope.row.status)">
              {{ getStatusText(scope.row.status) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="createTime" label="创建时间" width="180">
                <template #default="scope">
            {{ formatDate(scope.row.createTime) }}
                </template>
              </el-table-column>
            </el-table>
      
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="pagination.currentPage"
          v-model:page-size="pagination.pageSize"
          :page-sizes="[10, 20, 50, 100]"
          :total="pagination.total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
        </div>
      </el-card>
  </div>
</template>

<script setup>
import { ref, onMounted, onUnmounted } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import * as echarts from 'echarts'
import { getTaskList } from '@/api/task'
import { formatDate } from '@/utils/format'

const router = useRouter()
const loading = ref(false)
const tasks = ref([])
const statistics = ref({
  totalTasks: 0,
  completedTasks: 0,
  activeCompanies: 0,
  averageSalary: 0
})

// 图表引用
const statusChart = ref(null)
const typeChart = ref(null)
const salaryTrendChart = ref(null)
const salaryComparisonChart = ref(null)

// 图表实例
let statusChartInstance = null
let typeChartInstance = null
let salaryTrendChartInstance = null
let salaryComparisonChartInstance = null

// 时间范围选择
const salaryTrendPeriod = ref('30days')

// 分页配置
const pagination = ref({
  currentPage: 1,
  pageSize: 10,
  total: 0
})

// 加载所有数据
const loadData = async () => {
  loading.value = true
  try {
    // 加载任务列表
    await loadTasks()
    
    // 初始化图表
      initCharts()
    
  } catch (error) {
    console.error('加载数据失败:', error)
    ElMessage.error(error.message || '获取数据失败')
  } finally {
    loading.value = false
  }
}

// 加载任务列表并计算统计数据
const loadTasks = async () => {
  try {
    const response = await getTaskList()
    if (response && (response.data || Array.isArray(response))) {
      // 确保获取到的是数组
      const taskArray = Array.isArray(response) ? response : (response.data || [])
      tasks.value = taskArray
      
      // 更新分页总数
      pagination.value.total = taskArray.length
      
      // 计算统计数据
      calculateStatistics(taskArray)
      
      console.log('实际任务数量:', taskArray.length)
    } else {
      console.error('获取任务列表失败: 返回数据格式不正确')
      ElMessage.error('获取任务列表失败: 数据格式不正确')
    }
  } catch (error) {
    console.error('加载任务列表失败:', error)
    ElMessage.error('加载任务列表失败: ' + (error.message || '未知错误'))
  }
}

// 计算统计数据
const calculateStatistics = (taskList) => {
  if (!taskList || taskList.length === 0) {
    // 如果没有任务，重置所有统计数据
    statistics.value = {
      totalTasks: 0,
      completedTasks: 0,
      activeCompanies: 0,
      averageSalary: 0
    }
    return
  }
  
  // 总任务数 - 直接使用数组长度
  statistics.value.totalTasks = taskList.length
  
  // 计算不同状态的任务数和活跃企业数
  let completedCount = 0
  let totalSalary = 0
  const companies = new Set()
  
  for (const task of taskList) {
    // 统计活跃企业
    if (task.companyId) {
      companies.add(task.companyId)
    }
    
    // 统计完成任务数
    if (task.status === 'completed') {
      completedCount++
    }
    
    // 计算平均工资
    if (task.salary && !isNaN(parseFloat(task.salary))) {
      totalSalary += parseFloat(task.salary)
    }
  }
  
  statistics.value.activeCompanies = companies.size
  statistics.value.completedTasks = completedCount
  statistics.value.averageSalary = taskList.length > 0 
    ? (totalSalary / taskList.length).toFixed(2) 
    : 0
    
  console.log('统计数据:', statistics.value)
}

// 初始化所有图表
const initCharts = () => {
  initTypeChart()
  initStatusChart()
  initSalaryTrendChart()
  initSalaryComparisonChart()
}

// 初始化工种分布图表
const initTypeChart = () => {
  if (!typeChart.value) return
  
  // 计算工种分布
  const typeDistribution = {}
  tasks.value.forEach(task => {
    const jobType = task.jobType || '未指定'
    typeDistribution[jobType] = (typeDistribution[jobType] || 0) + 1
  })
  
  const typeData = Object.entries(typeDistribution).map(([name, value]) => ({
    name,
    value
  }))
  
  typeChartInstance = echarts.init(typeChart.value)
  typeChartInstance.setOption({
    title: {
      text: '工种分布分析',
      left: 'center'
    },
    tooltip: {
      trigger: 'item',
      formatter: '{b}: {c} ({d}%)'
    },
    legend: {
      orient: 'vertical',
      left: 'left',
      type: 'scroll'
    },
    series: [{
        name: '工种分布',
        type: 'pie',
      radius: '50%',
      data: typeData,
      emphasis: {
        itemStyle: {
          shadowBlur: 10,
          shadowOffsetX: 0,
          shadowColor: 'rgba(0, 0, 0, 0.5)'
        }
      }
    }]
  })
}

// 初始化委托成交分析图表
const initStatusChart = () => {
  if (!statusChart.value) return
  
  // 计算状态分布
  const statusDistribution = {
    published: 0,
    assigned: 0,
    completed: 0,
    cancelled: 0
  }
  
  tasks.value.forEach(task => {
    if (statusDistribution[task.status] !== undefined) {
      statusDistribution[task.status]++
    }
  })
  
  const statusData = [
    { value: statusDistribution.published, name: '已发布' },
    { value: statusDistribution.assigned, name: '进行中' },
    { value: statusDistribution.completed, name: '已完成' },
    { value: statusDistribution.cancelled, name: '已取消' }
  ]
  
  statusChartInstance = echarts.init(statusChart.value)
  statusChartInstance.setOption({
    title: {
      text: '委托成交分析',
      left: 'center'
    },
    tooltip: {
      trigger: 'item',
      formatter: '{b}: {c} ({d}%)'
    },
    legend: {
      orient: 'vertical',
      left: 'left'
    },
    series: [{
      name: '任务状态',
      type: 'pie',
      radius: '50%',
      data: statusData,
      emphasis: {
        itemStyle: {
          shadowBlur: 10,
          shadowOffsetX: 0,
          shadowColor: 'rgba(0, 0, 0, 0.5)'
        }
      }
    }]
  })
}

// 初始化薪资趋势图表
const initSalaryTrendChart = () => {
  if (!salaryTrendChart.value) return
  
  // 计算时间范围
  const endDate = new Date()
  let startDate = new Date()
  
  switch (salaryTrendPeriod.value) {
    case '7days':
      startDate.setDate(startDate.getDate() - 7)
      break
    case '3months':
      startDate.setMonth(startDate.getMonth() - 3)
      break
    case '30days':
    default:
      startDate.setDate(startDate.getDate() - 30)
      break
  }
  
  // 按日期分组计算平均薪资
  const salaryByDate = {}
  tasks.value.forEach(task => {
    if (task.createTime && task.salary) {
      const taskDate = new Date(task.createTime)
      if (taskDate >= startDate && taskDate <= endDate) {
        const dateStr = taskDate.toISOString().split('T')[0]
        if (!salaryByDate[dateStr]) {
          salaryByDate[dateStr] = { total: 0, count: 0 }
        }
        salaryByDate[dateStr].total += parseFloat(task.salary)
        salaryByDate[dateStr].count++
      }
    }
  })
  
  // 生成时间序列数据
  const dates = []
  const salaries = []
  const currentDate = new Date(startDate)
  
  while (currentDate <= endDate) {
    const dateStr = currentDate.toISOString().split('T')[0]
    dates.push(dateStr)
    
    const dateData = salaryByDate[dateStr]
    salaries.push(dateData && dateData.count > 0 
      ? (dateData.total / dateData.count).toFixed(2) 
      : 0)
    
    currentDate.setDate(currentDate.getDate() + 1)
  }
  
  salaryTrendChartInstance = echarts.init(salaryTrendChart.value)
  salaryTrendChartInstance.setOption({
    title: {
      text: '平台工资趋势',
      left: 'center'
    },
    tooltip: {
      trigger: 'axis'
    },
    xAxis: {
      type: 'category',
      data: dates,
      axisLabel: {
        rotate: 30
      }
    },
    yAxis: {
      type: 'value',
      name: '平均薪资(元)'
    },
    series: [{
      name: '平均薪资',
      data: salaries,
        type: 'line',
        smooth: true,
      areaStyle: {
        opacity: 0.3
      },
        lineStyle: {
        width: 3
      },
      markPoint: {
        data: [
          { type: 'max', name: '最高值' },
          { type: 'min', name: '最低值' }
        ]
      }
    }]
  })
}

// 初始化工种平均工资对比图表
const initSalaryComparisonChart = () => {
  if (!salaryComparisonChart.value) return
  
  // 计算各工种的平均工资
  const jobTypeSalary = {}
  const jobTypeCount = {}
  
  tasks.value.forEach(task => {
    if (task.jobType && task.salary && !isNaN(parseFloat(task.salary))) {
      const jobType = task.jobType
      if (!jobTypeSalary[jobType]) {
        jobTypeSalary[jobType] = 0
        jobTypeCount[jobType] = 0
      }
      jobTypeSalary[jobType] += parseFloat(task.salary)
      jobTypeCount[jobType]++
    }
  })
  
  // 计算平均工资
  const jobTypes = []
  const averageSalaries = []
  
  Object.keys(jobTypeSalary).forEach(jobType => {
    if (jobTypeCount[jobType] > 0) {
      jobTypes.push(jobType)
      averageSalaries.push((jobTypeSalary[jobType] / jobTypeCount[jobType]).toFixed(2))
    }
  })
  
  // 按平均工资排序
  const sortedData = jobTypes.map((jobType, index) => ({
    jobType,
    salary: parseFloat(averageSalaries[index])
  })).sort((a, b) => b.salary - a.salary)
  
  const sortedJobTypes = sortedData.map(item => item.jobType)
  const sortedSalaries = sortedData.map(item => item.salary)
  
  salaryComparisonChartInstance = echarts.init(salaryComparisonChart.value)
  salaryComparisonChartInstance.setOption({
    title: {
      text: '工种平均工资对比',
      left: 'center'
    },
    tooltip: {
      trigger: 'axis',
      axisPointer: {
        type: 'shadow'
      },
      formatter: '{b}: ¥{c}'
    },
    xAxis: {
      type: 'value',
      name: '平均工资(元)',
      nameLocation: 'end',
      nameGap: 15
    },
    yAxis: {
      type: 'category',
      data: sortedJobTypes,
      axisLabel: {
        interval: 0
      }
    },
    series: [{
        name: '平均工资',
        type: 'bar',
      data: sortedSalaries,
        itemStyle: {
          color: function(params) {
            // 颜色映射
            const colorList = [
              '#f56c6c', '#e6a23c', '#67c23a', '#409eff', 
              '#909399', '#9b59b6', '#f39c12', '#1abc9c'
            ]
            return colorList[params.dataIndex % colorList.length]
          },
          borderRadius: 5
        },
        label: {
          show: true,
          position: 'right',
        formatter: '¥{c}'
      }
    }]
  })
}

// 更新薪资趋势
const updateSalaryTrend = () => {
  initSalaryTrendChart()
}

// 获取状态样式
const getStatusType = (status) => {
  switch (status) {
    case 'published': return 'primary'
    case 'assigned': return 'success'
    case 'completed': return 'info'
    case 'cancelled': return 'danger'
    default: return 'info'
  }
}

// 获取状态文字
const getStatusText = (status) => {
  switch (status) {
    case 'published': return '已发布'
    case 'assigned': return '进行中'
    case 'completed': return '已完成'
    case 'cancelled': return '已取消'
    default: return '未知状态'
  }
}

// 查看任务详情
const handleRowClick = (row) => {
  router.push(`/task/${row.id}`)
}

// 分页处理
const handleSizeChange = (size) => {
  pagination.value.pageSize = size
}

const handleCurrentChange = (page) => {
  pagination.value.currentPage = page
}

// 窗口大小变化时调整图表大小
const handleResize = () => {
  if (statusChartInstance) {
    statusChartInstance.resize()
  }
  if (typeChartInstance) {
    typeChartInstance.resize()
  }
  if (salaryTrendChartInstance) {
    salaryTrendChartInstance.resize()
  }
  if (salaryComparisonChartInstance) {
    salaryComparisonChartInstance.resize()
  }
}

// 组件挂载时加载数据
onMounted(() => {
  loadData()
  window.addEventListener('resize', handleResize)
})

// 组件卸载时移除事件监听
onUnmounted(() => {
  window.removeEventListener('resize', handleResize)
})
</script>

<style scoped>
.analytics-container {
  padding: 20px;
}

.data-overview {
  margin-bottom: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.card-value {
  font-size: 24px;
  font-weight: bold;
  color: #409EFF;
  text-align: center;
}

.charts-container {
  margin-bottom: 20px;
}

.chart {
  height: 300px;
}

.task-list-card {
  margin-top: 20px;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: center;
}
</style> 